const app = getApp()
const util = require('../../utils/util');
const WXAPI = require('../../wxapi/main')

Page({
  // mixins: [require('../../mixin/common')],
  /**
   * 页面的初始数据
   */
  data: {
    theme: 'light',
    mode: '', // 模式(care：关怀模式)
    reqTypeList: [{ code: 'resource', val: '找客户' },  { code: 'question', val: '求解答' }, { code: 'meeting', val: '找会议'}],
    reqTypeSelectIndex: 0,
    reqCompany: '',
    reqBrand: '',
    reqDesc: '',  
    reqDept: '',
    isReward: false,
    remark: '',
    reqMeetingInst: '',
    reqMeetingStart: '',
    reqMeetingEnd: '',
    reqMeetingAddress: '',
    findTypeList: ['精准寻找客户', '寻找相似客户'],
    findTypeIndex: 0,
    rewardCode: '',
    rewardName: '',
    partUserInfo: null,
    currentScore: 0,
    lock: false,
    rewardList: [],
    rewardSelectIndex:0,
    checkValue: '',
  },

  radioBtn: function (e) {
    console.log('r ', e)
    var index = e.currentTarget.dataset.index;//获取当前点击的下标
    // var index = e.detail.value;
    var checkboxArr = this.data.rewardList;//选项集合
    if (checkboxArr[index].checked) return;//如果点击的当前已选中则返回
    checkboxArr.forEach(item => {
     item.checked = false
    })
    checkboxArr[index].checked = true;//改变当前选中的checked值
    console.log('index ', index)
    this.setData({
      rewardList: checkboxArr,
      rewardSelectIndex: index
    });
    },
    // radioChange: function (e) {
    // var checkValue = e.detail.value;
    // this.setData({
    //  checkValue: checkValue
    // });
    // },

  changeReqType: function (e) {
    var that = this;
    var _reqTypeSelectIndex = e.detail.value
    // var _selectedReqType = that.data.reqTypeList[_reqTypeSelectIndex]
    // console.log('selected type ', _selectedReqType)    
    that.setData({
      reqTypeSelectIndex: _reqTypeSelectIndex
    })
    if (_reqTypeSelectIndex == 2)  {
      that.setData({
        reqMeetingEnd: '2024-01-01',
        reqMeetingStart: '2024-01-01'
      })
    } 
  },
  changeFindType(e) {
    var that = this;
    var _findTypeIndex = e.detail.value
    // var _selectedReqType = that.data.reqTypeList[_reqTypeSelectIndex]
    console.log('find type index ', _findTypeIndex)    
    that.setData({
      findTypeIndex: _findTypeIndex
    })
  },
  changeReward(e) {
    var that = this;
    var _rewardSelectIndex = e.detail.value
    // var _selectedReqType = that.data.reqTypeList[_reqTypeSelectIndex]
    // console.log('selected type ', _selectedReqType)    
    that.setData({
      rewardSelectIndex: _rewardSelectIndex
    })
  },
  bindCompanyChange(e) {
    console.log('change company ', e.detail.value);
    this.setData({
      reqCompany: e.detail.value,
    });
  },
  bindBrandChange(e) {
    console.log('change brand ', e.detail.value);
    this.setData({
      reqBrand: e.detail.value,
    });
  },
  bindDeptChange(e) {
    console.log('change dept ', e.detail.value);
    this.setData({
      reqDept: e.detail.value,
    });
  },
  bindRemarkChange(e) {
    console.log('change remark ', e.detail.value);
    this.setData({
      remark: e.detail.value,
    });
  },
  bindDescChange(e) {
    console.log('exec desc change ', e)
    this.setData({
      reqDesc: e.detail.value,
    });
  },
  bindMeetingInstChange(e) {
    console.log('exec reqMeetingInst change ', e)
    this.setData({
      reqMeetingInst: e.detail.value,
    });
  },
  bindMeetingAddrChange(e) {
    console.log('exec reqMeetingInst change ', e)
    this.setData({
      reqMeetingAddress: e.detail.value,
    });
  },
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      reqMeetingStart: e.detail.value
    })
  },
  bindEndDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      reqMeetingEnd: e.detail.value
    })
  },
  bindRewardChange(e) {
    console.log('reward', e)
    this.setData({
      isReward: e.detail.value
    })
  },

  btnSubmit() {
    let that = this
    var _partUserInfo = wx.getStorageSync('partUserInfo')
    if (!_partUserInfo) {
      app.goLoginPageTimeOut()
      return
    } else {
      that.setData({
        partUserInfo: _partUserInfo
      })
    }   
    var skey = wx.getStorageSync('loginFlag')
    console.log('partUserInfo', _partUserInfo)
    console.log('skey ', skey)
    console.log('btn submit ', that.data.reqCompany, that.data.reqBrand, that.data.reqDesc)
    // build && check
    let errors = []
    let _reqTypeSelectIndex = that.data.reqTypeSelectIndex
    let _findTypeIndex = that.data.findTypeIndex
    var _reqDesc = ''
    if (_reqTypeSelectIndex == 0 && _findTypeIndex == 0) {
      that.verifyData('reqCompany', that.data.reqCompany, 50, errors)
      that.verifyData('reqBrand', that.data.reqBrand, 50, errors)
      that.verifyData('reqDept', that.data.reqDept, 50, errors)
      that.verifyData('remark', that.data.remark, 50, errors)
      _reqDesc = '请大佬帮忙介绍'+ that.data.reqBrand +'的'+ that.data.reqDept +'的负责人'+ that.data.remark+'洽谈合作'
    }if (_reqTypeSelectIndex == 0 && _findTypeIndex == 1) {
      that.verifyData('reqCompany', that.data.reqCompany, 50, errors)
      that.verifyData('reqBrand', that.data.reqBrand, 50, errors)
      _reqDesc = '求前辈帮忙解答与'+ that.data.reqBrand +'做同样业务的公司有哪些？越完整越好'
    } else if (_reqTypeSelectIndex == 1) {
      that.verifyData('reqDesc', that.data.reqDesc, 500, errors)
      _reqDesc = that.data.reqDesc
    } else if (_reqTypeSelectIndex == 2) {
      that.verifyData('reqMeetingInst', that.data.reqMeetingInst, 50, errors)
      that.verifyData('reqMeetingAddress', that.data.reqMeetingAddress, 50, errors)
      that.verifyData('reqMeetingStart', that.data.reqMeetingStart, 20, errors)
      that.verifyData('reqMeetingEnd', that.data.reqMeetingEnd, 20, errors)
      _reqDesc = '找'+ that.data.reqMeetingStart+'至'+ that.data.reqMeetingEnd +'在'+ that.data.reqMeetingAddress +'举办的' + that.data.reqMeetingInst + '会议/沙龙'
    }


    console.log('error ', errors)
    // 
    if (errors.length > 0) {
      wx.showToast({
        title: errors[0],
        icon: 'none'
      })
      return
    }
    // check score
    if (that.data.currentScore < 1) {
      wx.showModal({
        title: '发布条件',
        content: '非常抱歉，您现在未达到发布条件，请分享邀请一位好友注册“打粮人”，或在需求市场洽谈一个需求。',
        complete: (res) => {
          if (res.cancel) {
            console.log('exec cancel ...')
          }
      
          if (res.confirm) {
            console.log('exec confirm ...')
          }
        }
      })
      return
    }
    // isReward, reqCompany, reqBrand, reqDept,
    // reqMeetingInst, reqMeetingStart, reqMeetingEnd, reqMeetingAddress, remark
    let _rewardSelectIndex = that.data.rewardSelectIndex
    let _rewardCode = that.data.rewardList[_rewardSelectIndex].giftCode
    let _rewardName = that.data.rewardList[_rewardSelectIndex].giftName
    let postData = {skey, 
      type: that.data.reqTypeList[that.data.reqTypeSelectIndex].code, 
      reqTitle: _reqDesc.substring(0,100), 
      reqDesc: _reqDesc, 
      isReward: that.data.isReward?'1':'0',
      reqCompany: that.data.reqCompany, 
      reqBrand: that.data.reqBrand,
      reqDept: that.data.reqDept,
      remark: that.data.remark,
      reqMeetingInst: that.data.reqMeetingInst,
      reqMeetingStart: that.data.reqMeetingStart,
      reqMeetingEnd: that.data.reqMeetingEnd,
      reqMeetingAddress: that.data.reqMeetingAddress,
      findTyle: that.data.findTypeIndex,
      rewardCode: _rewardCode,
      rewardName: _rewardName,
    }
    console.log('go on ... ', postData)
    wx.showLoading({
      title: '处理中,请稍等',
    })
    WXAPI.saveReq(postData)
    .then(function(res) {
      console.log('save req ', res)
      if (res.code === 0) {
        var _result  = res.data
        console.log('req save ', _result)         
        // wx.showToast({
        //   title: '发布成功',
        //   icon: 'success'
        // })
        that.setData({
          reqTypeSelectIndex: 0,
          reqCompany: '',
          reqBrand: '',
          reqDesc: '',  
          reqDept: '',
          isReward: false,
          remark: '',
          reqMeetingInst: '',
          reqMeetingStart: '',
          reqMeetingEnd: '',
          reqMeetingAddress: '',
        })
        wx.hideLoading()
        wx.switchTab({
          url: '/pages/req-mgr/index',
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    })
  },

  verifyRemark(val, len, errors) {
    let that = this
    if (val === '' || val === undefined) {
      return
    }
    if (val.length > len) {
      let codeDesc = that.transCodeToDesc('remark')
      errors.push(codeDesc + '超长了')
    }
  },
  // 关键字 值 条件 错误集合
  verifyData(key, val, len, errors) {
    let that = this
    if (key === 'remark') {
      return
    }
    if (val === '' || val === undefined) {
      let codeDesc = that.transCodeToDesc(key)
      errors.push(codeDesc + '为空了')
    }
    if (val.length > len) {
      let codeDesc = that.transCodeToDesc(key)
      errors.push(codeDesc + '超长了')
    }
  },
  transCodeToDesc(code) {
    switch (code) {
      case 'reqCompany':
        return '客户名称(全称)'
      case 'reqBrand':
        return '客户名称(简称)'
      case 'reqDesc':
        return '需求描述'
      case 'reqDept':
        return '部门'
      case 'remark':
        return '非必填'
      case 'reqMeetingInst':
        return '行业'
      case 'reqMeetingAddress':
        return '举办城市'
      case 'reqMeetingStart':
        return '会议起始日期'
      case 'reqMeetingEnd':
        return '会议结束日期'      
      default:
        return '未知'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('init on load')
    // date initial 
    let currentDate = new Date()
    let strdate = util.formatDate(currentDate)
    this.setData({
      date: strdate
    })

    WXAPI.loadGift().then(
      ret => {
        console.log('ret gift ', ret)
        if (ret.code === 0) {
          let _rewardList = ret.data.map((row, index)=> {
            return {...row, checked: false}
          })
          this.setData({
            rewardList: _rewardList
          })
        }
      }
    )
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('init on show...')
    let that = this
    var skey = wx.getStorageSync('loginFlag')
    if (skey) {
      console.log('init score ')
      WXAPI.loadCompleteUserInfo({skey})
      .then(resUser => {
        console.log('current user ', resUser)
        if (resUser.code === 0 ) {
          let userAllInfo = resUser.data
          that.setData({
            currentScore: userAllInfo.dlScore
          })
        }
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})